<?php

class WPSPO_Defis extends WPSPO_Object {
    
    var $errors = array();

    
    function save($user, $content, $title, $projet, $status='publish') {
        global $wpdb;
         
        if(isset($user) && is_numeric($user)) {
            $post = array(
                'post_author' => $user,
                'post_content' => $content,
                'post_excerpt' => wpspo_cutString($content, 0, 100, '...'),
                'post_status' => $status,
                'post_name' => sanitize_title($title),
                'comment_status' => 'open',
                'ping_status' => 'closed',
                'post_date_gmt' => date("Y-m-d H:i:s"), 
                'post_title' => wp_strip_all_tags($title),
                'post_type' => 'defi',
            );
            $post_id = wp_insert_post( $post, $wp_error );
            //update_post_meta($post_id, 'wpspo_choixprojets', $projet);
            add_post_meta($post_id, 'wpspo_choixprojets', $projet, true);
            if($post_id) {
                return $post_id;
            } else {
                return 'Erreur';
            }
        
        } else {
            return 'Erreur';
        }
        
    }
    function update($id, $texte, $title) {
        
        if( isset($id) && is_numeric($id) ) {
            
            $updateDefi = array();
            $updateDefi['ID'] = $id;
            $updateDefi['post_title'] = $title;
            $updateDefi['post_content'] = $texte;
            $updateDefi['post_name'] = wpspo_generate_slug($title);
            
            if(wp_update_post( $updateDefi )) {
                return $id;
            }
            
        } else {
            die('Erreur update');
        }
  
    }
    function updateStatus($id, $status) {
        $updateDefi['post_status'] = $status; 
        if(wp_update_post( $updateDefi )) {
            return $id;
        }
    }
    
    function saveOptions($user, $idProjet, $idDefi, $tab) {
        global $wpdb;
        $data = array(
            'defis_id_projet' => $idProjet,
            'defis_id_defi' => $idDefi,
            'defis_id_user' => $user,
            'defis_option_value' => $tab        
        );
        $result = $wpdb->insert(WSPO_DEFIS, $data);
        if(!$result) {
            return 'Erreur save options defis';
        }
        
    }
    
    function updateOptions($idProjet, $idDefi, $tab, $statut = 1) {
        global $wpdb;
        $data = array(
            'defis_option_value' => $tab        
        );
        $where = array( 
            'defis_id_defi' => $idDefi, 
            'defis_id_projet' => $idProjet, 
            'defis_id_actif' => $statut
        );
        $result = $wpdb->update(WSPO_DEFIS, $data, $where);
        if(!$result) {
            return 'Erreur save options defis';
        }
        
    }
    
    function get($idPost, $iduser = "") {
       
        global $wpdb;
        if( (isset($iduser) && is_numeric($iduser)) && is_numeric($idPost) ) {
            
            $getPost = query_posts( array(
                'post_type'   => 'defi',
                'post_id'   => $idPost,
                'numberposts' => 1, 
                'orderby'     => 'post_date',
                'post_parent' => 0,
                'post_status' => 'publish',
                'order'       => 'DESC',
                'author' => $iduser
                ) );
            
            return $getPost;
            
        } elseif ( isset($idPost) && is_numeric($idPost) ) {
            
            $getPost = get_post($idPost, OBJECT);
            return $getPost;
            
        } else {
            
            exit('Erreur get post');
        }
    }
    
    function get_optionsById($id, $idUser = '') {
        global $wpdb;
        if(isset($idUser)) {
            $result = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM ". WSPO_DEFIS . " WHERE defis_id_defi = %d AND defis_id_user = %d LIMIT 1", $id, $idUser), 'OBJECT' );
        } else {
            $result = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM ". WSPO_DEFIS . " WHERE defis_id_defi = %d LIMIT 1", $id), 'OBJECT' );
        }
        //echo "SELECT * FROM ". WSPO_DEFIS . " WHERE defis_id_defi='".$id."' AND defis_id_user='".$idUser."' LIMIT 1";
        if($result) {
            return $result;
        }        
    }
    // EN DOUBLE ??
    function get_options($id) {
        global $wpdb;
        $result = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM ". WSPO_DEFIS . " WHERE defis_id_defi = %d LIMIT 1", $id ), 'OBJECT' );
        if($result) {
            return $result;
        }
    }
    
    function get_optionsByProjet($idprojet) {
        global $wpdb;
        $result = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM ". WSPO_DEFIS . " WHERE defis_id_projet= %d LIMIT 1", $idprojet ), 'OBJECT');
        if($result) {
            return $result;
        } else {
            return __('No challenge proposed', 'sponsorpress').__('Be the first to organize a challenge for this project', 'sponsorpress').' : <a href="'.get_permalink(WPSPO_ID_ORGANISER).'">'._('Click here', 'sponsorpress').'</a>';
        }
        
    }
    
    function get_idProjet($idDefi) {
        global $wpdb;
        $result = $wpdb->get_var( $wpdb->prepare( "SELECT defis_id_projet FROM ". WSPO_DEFIS . " WHERE defis_id= %d LIMIT 1", $idDefi ), 'OBJECT');
        return $result;
    }
    
    /*
     * Compte le nombre de défis actifs pour l'user sur un projet spécifique
     */
    function get_countByProjet($idprojet, $iduser = '') {
        global $wpdb;
        if($iduser>0) { 
            $defis_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM ".WSPO_DEFIS." WHERE defis_id_actif = %d AND defis_id_projet = %d AND defis_id_user = %d ", 1, $idprojet, $iduser ) );
        } else {
            $defis_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM ".WSPO_DEFIS." WHERE defis_id_actif = %d AND defis_id_projet = %d ", 1, $idprojet ) );
        }
        return $defis_count;
    }
    
    /*
     * Compte le nombre de défis actifs pour l'user sur un defi spécifique
     */
    function get_countByUser($id, $iduser) {
        global $wpdb;
        $defis_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM ".WSPO_DEFIS." WHERE defis_id_defi = %d AND defis_id_user = %d ", $id, $iduser ) );
        return $defis_count;
    }
    
        
    /*
     * Compte le nombre de défis actifs pour l'user sur un defi et un projet spécifique
     */
    function get_countByUserByProjet($id, $id_u, $id_p) {
        global $wpdb;
        $defis_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM ".WSPO_DEFIS." WHERE defis_id_defi = %d AND defis_id_user = %d AND defis_id_projet = %d ", $id, $id_u, $id_p ) );
        return $defis_count;
    }
    
    
    /*
     * Supprime un défis particulier
     */
    function delete($user, $iddefi) {
		global $wpdb;
        // Supprime dans la table des défis 'wp_sponsorpress_defis'
		$deleteOptions = "DELETE FROM ". WSPO_DEFIS . " WHERE defis_id_defi = %d AND defis_id_user = %d LIMIT 1";
        $resultOptions = $wpdb->query( $wpdb->prepare( $deleteOptions, $iddefi, $user ) );
        
		if($resultOptions) {
            return 'Défis supprimé';
        } else {
            return 'Erreur suppression défis';
        }
        
	}
    
    function get_list($numb = 10, $idUser = '') {
        global $wpdb;
        
        $listeDefi = get_posts( array(
            'post_type'   => 'defi',
            'numberposts' => $numb, 
            'orderby'     => 'post_date',
            'post_parent' => 0,
            'order'       => 'DESC',
            'author' => $idUser
            ) );

        if ( count( $listeDefi ) > 0 ) {
            return $listeDefi;
        }
    }
    
    function listForMap() {
        global $wpdb;
        
        $listeProjets = get_posts( array(
            'post_type'   => 'defi',
            'orderby'     => 'post_date',
            'post_parent' => 0,
            'post_status' => 'publish',
            'order'       => 'DESC',
            ) );

        if ( count( $listeProjets ) > 0 ) {
            return $listeProjets;
        }
    }
    
    function listByProjet($idProjet) {
        global $wpdb;
        
        if(!$idProjet) { die('Aucun projet sélectionné'); }

        $listeProjets = get_posts( array(
            'post_type'   => 'defi',
            'meta_query' => 'wpspo_choixprojets',
            'meta_value' => $idProjet,
            'numberposts' => 10, 
            'orderby'     => 'post_date',
            'post_parent' => 0,
            'post_status' => array('publish', 'archive'),
            'order'       => 'DESC'
            ) );

        $count = count( $listeProjets );
        if ( $count > 0 ) {
            return $listeProjets;
        }
    }
    
} 